package priv.happy.mealpickpro.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import priv.happy.mealpickpro.domain.Food;
import priv.happy.mealpickpro.dto.AddFoodDTO;
import priv.happy.mealpickpro.dto.FoodDTO;
import priv.happy.mealpickpro.emum.SystemStatusCode;
import priv.happy.mealpickpro.mapper.FoodMapper;
import priv.happy.mealpickpro.service.FoodService;
import priv.happy.mealpickpro.service.FoodTagService;
import priv.happy.mealpickpro.service.TagService;
import priv.happy.mealpickpro.vo.ApiResponse;
import priv.happy.mealpickpro.vo.FoodVO;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: HAPPY
 * @Project_name: MealPick
 * @Package_name: priv.happy.mealpick.controller
 * @Date: 2023/7/2 17:52
 * @Description:
 */
@RestController
@RequestMapping("/api/v2/food")
public class FoodController {
    @Autowired
    FoodService foodService;
    @Autowired
    TagService tagService;
    @Autowired
    FoodMapper foodMapper;
    @Autowired
    FoodTagService foodTagService;
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    /**
     * 获取所有食物
     *
     * @param current 当前页编号，从1开始，每次递增1
     * @param size    每页数量
     * @return 返回当前页所有食物
     */
    @GetMapping()
    public ApiResponse<List<FoodVO>> doGetByPage(Long current, Long size, Integer userId) {
        ApiResponse<List<FoodVO>> listApiResponse = new ApiResponse<>();
        try {
            Page<Food> foodPage = new Page<>(current, size);
            foodPage = foodService.page(foodPage, new QueryWrapper<Food>()
                    .eq("post_user_id", userId));
            List<FoodVO> foodVOPage = new ArrayList<>();

            for (int i = 0; i < foodPage.getTotal() - (current - 1) * size; i++) {
                foodVOPage.add(new FoodVO().setName(foodPage.getRecords().get(i).getName())
                        .setId(foodPage.getRecords().get(i).getId()).setDescription(foodPage.getRecords().get(i).getDescription())
                        .setPhotoUrl(foodPage.getRecords().get(i).getPhotoUrl()).setPrice(foodPage.getRecords().get(i).getPrice())
                        .setTagList(tagService.getFoodTagList(foodPage.getRecords().get(i).getId())));
            }
            listApiResponse.setData(foodVOPage).setCode(200).setMessage("查询成功").setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            listApiResponse.setCode(500).setMessage("拉取食物信息失败").setSuccess(false);
        }
        return listApiResponse;
    }

    /**
     * 根据名称查询某个用户的食物
     *
     * @param foodName 要查询的食物名称
     * @param userId   当前用户的id
     * @return 返回查询的结果集合
     */
    @GetMapping("/getOne")
    public ApiResponse<List<Food>> doGetFoodByName(String foodName, Integer userId) {
        ApiResponse<List<Food>> listApiResponse = new ApiResponse<>();
        try {
            listApiResponse.setData(foodService.list(new QueryWrapper<Food>()
                            .like("name", foodName)
                            .eq("post_user_id", userId)))
                    .setCode(200).setMessage("查询成功").setSuccess(true);
        } catch (Exception e) {
            listApiResponse.setCode(500).setMessage("查询食物信息失败").setSuccess(false);
        }
        return listApiResponse;
    }

    /**
     * 根据用户选择的食物、价格等生成可以选择的食物
     *
     * @param foodDTO 用户选择的食物筛选基本信息
     * @return 返回生成的食物
     */
    @PostMapping("/pickFood")
    public ApiResponse<FoodVO> mealPick(@RequestBody FoodDTO foodDTO) {
        ApiResponse<FoodVO> foodApiResponse = new ApiResponse<>();
        // 判断有没有食物
        if (foodService.count(new QueryWrapper<Food>()
                .eq("post_user_id", foodDTO.getUserId())) <= 0) {
            return foodApiResponse.setCode(SystemStatusCode.BAD_REQUEST.getCode())
                    .setMessage("请先至少添加一个食物！")
                    .setSuccess(false);
        }
        FoodVO pickFood = foodService.pickFood(foodDTO);
        if (pickFood != null) {
            foodApiResponse.setData(pickFood).setCode(SystemStatusCode.SUCCESS.getCode())
                    .setMessage("食物选择成功").setSuccess(true);
        } else {
            foodApiResponse.setCode(SystemStatusCode.SERVICE_UNAVAILABLE.getCode())
                    .setMessage("食物选择失败").setSuccess(false);
        }
        return foodApiResponse;
    }

    /**
     * 新增食物
     *
     * @param addFoodDTO 新增的食物信息
     * @return 返回成功与否
     */
    @PostMapping()
    public ApiResponse<String> doAddFood(@RequestBody AddFoodDTO addFoodDTO) {
        ApiResponse<String> listApiResponse = new ApiResponse<>();
        try {
            if (addFoodDTO.getAddressId() == null || addFoodDTO.getAddressId() < 0) {
                return listApiResponse.setSuccess(false)
                        .setCode(SystemStatusCode.BAD_REQUEST.getCode())
                        .setMessage("请先在个人界面→地址管理添加一个地址哦");
            }
            switch (foodService.addFood(addFoodDTO)) {
                case 0:
                    listApiResponse.setCode(SystemStatusCode.SUCCESS.getCode())
                            .setMessage("成功添加新食物").setSuccess(true);
                    break;
                case 1:
                    listApiResponse.setCode(SystemStatusCode.BAD_REQUEST.getCode())
                            .setMessage("图片格式选择错误").setSuccess(false);
                    break;
                default:
                    listApiResponse.setCode(SystemStatusCode.SERVICE_UNAVAILABLE.getCode())
                            .setMessage("添加新食物失败").setSuccess(false);
            }
        } catch (Exception e) {
            listApiResponse.setCode(SystemStatusCode.SERVICE_UNAVAILABLE.getCode())
                    .setMessage("添加新食物失败").setSuccess(false);
        }
        return listApiResponse;
    }

    /**
     * 修改食物信息
     *
     * @param modifyFoodDTO 要修改的食物信息
     * @return 返回成功与否
     */
    @PutMapping
    public ApiResponse<String> doModifyFood(@RequestBody AddFoodDTO modifyFoodDTO) {
        ApiResponse<String> listApiResponse = new ApiResponse<>();
        try {
            switch (foodService.modifyFood(modifyFoodDTO)) {
                case 0:
                    listApiResponse.setCode(SystemStatusCode.SUCCESS.getCode())
                            .setMessage("成功修改食物信息").setSuccess(true);
                    break;
                case 1:
                    listApiResponse.setCode(SystemStatusCode.BAD_REQUEST.getCode())
                            .setMessage("图片格式选择错误").setSuccess(false);
                    break;
                default:
                    listApiResponse.setCode(SystemStatusCode.SERVICE_UNAVAILABLE.getCode())
                            .setMessage("修改食物信息失败").setSuccess(false);
            }
        } catch (Exception e) {
            listApiResponse.setCode(SystemStatusCode.SERVICE_UNAVAILABLE.getCode())
                    .setMessage("修改食物失败").setSuccess(false);
        }
        return listApiResponse;
    }


    /**
     * 根据id删除一个食物
     *
     * @param foodId 要删除的食物id
     * @return 返回删除成功与否
     */
    @DeleteMapping()
    public ApiResponse<String> doRemoveFoodById(Integer foodId, Integer userId) {
        ApiResponse<String> listApiResponse = new ApiResponse<>();
        if (foodService.removeFoodById(foodId, userId)) {
            listApiResponse.setCode(SystemStatusCode.SUCCESS.getCode())
                    .setMessage("成功删除食物！").setSuccess(true);
        } else {
            listApiResponse.setCode(SystemStatusCode.UNAUTHORIZED.getCode())
                    .setMessage("权限不足，删除食物失败，请联系管理员删除")
                    .setSuccess(false);
        }
        return listApiResponse;
    }
}
